=pod
 * DataCenter.pm
 * 
 * Copyright (C) 2012 Elena Shishkina
 * 
 * This file is part of ServerInventory.
 * 
 * ServerInventory is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * ServerInventory is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with ServerInventory.  If not, see <http://www.gnu.org/licenses/>.
=cut

use utf8;
use 5.12.0;
package ServerInventory::DataCenter;
use Moose;
use DBI;
use JSON;

sub Process {
    my $self = shift;
    my $r = shift;
    $self->{request} = $r;
    given ($r->param('mode')) {
        when ('edit') {
            $self->Edit();
        }
        when ('remove') {
            $self->Remove();
        }
        when ('add') {
            $self->Add();
        }
        when ('resize') {
            $self->Resize();
        }
        when ('move_entrance') {
            $self->MoveEntrance();
        }
        default {
            $self->LoadData();
        }
    }
}

sub LoadData {
    my $self = shift;
    my $data = $self->{request}->{dbh}->selectall_arrayref('select * from dcs', {Slice => {}}) || [];
    $self->{request}->render(json => $data);
}

sub Remove {
    my $self = shift;
    my $r = $self->{request};
    my $sth = $r->{dbh}->prepare('delete from dcs where id = ?');
    if ($sth->execute($r->param('id'))) {
        $r->render(json => {result => 'RESULT_OK'});
    } else {
        $r->render(json => {result => 'ERROR', message => $sth->errstr});
    }
    $sth->finish;
}

sub Add {
    my $self = shift;
    my $r = $self->{request};
    my $sth = $r->{dbh}->prepare('insert into dcs (name, address, power, notes) values (?, ?, ?, ?); select max(id) from dcs;');
    if ($sth->execute($r->param('name'), $r->param('address'), $r->param('power'), $r->param('notes'))) {
        $r->render(json => {result => 'RESULT_OK', id => $sth->fetchrow_array});
    } else {
        $r->render(json => {result => 'ERROR', message => $sth->errstr});
    }
    $sth->finish;
}

1;
